const UserInfo = require("../models/UserInfo");
const { Op } = require("sequelize");
const jwt = require("../tools/jwt");
const { jwtSecret } = require("../tools/config");
// const { encrypt } = require('../tools/cipherCode');
// const key = 'cobot'

module.exports = class UserManager {
  /**
   * 增加一个user
   * @param {*} userObj
   * @returns
   */
  static async addAdmin(userObj) {
    // let encryptUser;
    // if(userObj.passwd){
    //   encryptUser = {...userObj};
    //   encryptUser.passwd = encrypt(userObj.passwd,key);
    // }
    // console.log('encryptUser',encryptUser)
    const result = await UserInfo.create(userObj);
    return result.toJSON();
  }

  /**
   * 删除一个user
   * @param {*} userId
   */
  static async deleteAdmin(userId) {
    const result = await UserInfo.destroy({
      where: {
        id: userId,
      },
    });
  }
  /**
   * 批量删除user
   * @param {*} id
   */
  static async bulkDelete(params) {
    let promises;
    const _this = this;
    const delRes = [];

    if (params.length > 0) {
      promises = params.map(async (item) => {
        const res = await _this.deleteAdmin(item);
        delRes.push(res);
      });
    }
    await Promise.all(promises);
  }

  /**
   * 更新user
   * @param {*} userId
   * @param {*} userObj
   */
  static async updateAdmin(userId, userObj) {
    await UserInfo.update(userObj, {
      where: {
        id: userId,
      },
    });
    const result = await UserInfo.findOne({
      where: {
        id: userId,
      },
    });
    return result;
  }

  /**
   * 查询所有的user
   * @returns
   */
  static async getAllAdmin() {
    const result = await UserInfo.findAll();
    return JSON.parse(JSON.stringify(result));
  }

  /**
   *分页查询 user
   * @returns
   */
  static async find(page = 1, limit = 10, name, level, searchLevel) {
    const where = {};
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`,
      };
    }
    //其他角色不能看到工程师账号；
    if (level && level != 5) {
      if (level == 1) {
        if (searchLevel === "null") {
          where.level = {
            [Op.not]: [5, level],
          };
        } else {
          where.level = {
            [Op.eq]: [searchLevel],
          };
        }
      } else if (level == 2) {
        where.level = {
          [Op.not]: [5, 1, 2],
        };
      } else {
        where.level = {
          [Op.not]: 5,
        };
      }
    }
    const result = await UserInfo.findAndCountAll({
      where,
      offset: (page - 1) * limit,
      limit: +limit,
      order: [["createdAt", "DESC"]],
    });
    return JSON.parse(JSON.stringify(result));
  }
  /**
   * 根据账号查询user
   * @returns
   */
  static async getAdminByUser(user) {
    const result = await UserInfo.findOne({
      where: {
        user: user,
      },
    });
    if (result === null) {
      console.log("getAdminByUser user Not found!", user);
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }
  /**
   * 根据id查询user
   * @returns
   */
  static async getAdminById(id) {
    const result = await UserInfo.findOne({
      where: {
        id,
      },
    });
    if (result === null) {
      console.log("getAdminById user Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }
  /**
   * 根据level查询user
   * @returns
   */
  static async getAdminByLevel(level) {
    const result = await UserInfo.findOne({
      where: {
        level: level,
      },
    });
    if (result === null) {
      console.log("getAdminByLevel user Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }
  /**
   * 登录
   * @returns
   */
  static async login(loginId, loginPwd) {
    const resultByUser = await UserInfo.findOne({
      where: {
        user: loginId,
      },
    });

    if (resultByUser === null) {
      console.log("login user Not found!");
      throw new Error("用户或密码错误！");
    } else if (resultByUser.user != loginId) {
      console.log("resultByUser", resultByUser.user);
      throw new Error("用户或密码错误！");
    } else {
      const result = await UserInfo.findOne({
        where: {
          user: loginId,
          passwd: loginPwd,
        },
      });
      if (result === null) {
        throw new Error("用户或密码错误！");
      } else {
        const user = JSON.parse(JSON.stringify(result));
        const token = await jwt.sign({ userId: user.id }, jwtSecret);
        // 更新用户的当前有效token
        await UserInfo.update(
          { currentToken: token },
          { where: { id: user.id } }
        );
        return { ...user, currentToken: token, token };
      }
    }
  }
  /**
   * 验证token
   * @returns
   */
  static async verifyToken(token) {
    try {
      const decoded = await jwt.verify(token, jwtSecret);
      const user = await UserInfo.findOne({
        where: {
          id: decoded.userId,
          currentToken: token,
        },
      });
      if (user === null) {
        throw new Error("无效的token！");
      } else {
        return user;
      }
    } catch (err) {
      throw new Error("token验证失败！");
    }
  }
};
